import json
import os
import hashlib
import random
import sendmail

bar = """
    欢迎来到xxx网站
1、用户登录
2、用户注册
3、退出
"""
# if [ ! -f ./user.json ]
if not os.path.isfile("./user.json"):
    data = {"用户名": "", "密码": "", "邮箱": ""}
    with open("user.json", "w") as f:
        json.dump([data], f, ensure_ascii=False, indent="  ")

def number():
    return random.randrange(100000, 999999)

def number_check(user):
    n = number()
    sendmail.mail_to(users=user, num=n)
    while True:
        user_n = input("请输入你的验证码: ")
        if user_n == str(n):
            print("验证码正确")
            break
        else:
            print("验证码错误")
    return True

def hash_password(password):
    p = hashlib.md5(password.encode())
    return p.hexdigest()

def write_userdata(filepath="./user.json", data=None):
    with open(filepath, "w") as f:
        json.dump(data, f, ensure_ascii=False, indent="  ")
    return True


def read_userdata(filepath="./user.json"):
    with open(file=filepath, mode="r") as f:
        return json.load(f)
def reg_user():
    # 获取当前已存在的所有用户信息
    userdata = read_userdata()
    # 需要获取用户的哪些信息
    data = ["用户名", "密码", "邮箱"]
    # 将上面的信息初始化为一个字典
    data = dict.fromkeys(data)
    # 循环取字典中的每一个键，并且让用户填充信息
    for i in data:
        data[i] = input(f"请输入你的{i}:")

    if [x for x in userdata if x["用户名"] == data["用户名"]]:
        print("用户已存在")
    else:
        data["密码"] = hash_password(data["密码"])
        userdata.append(data)
        write_userdata(data=userdata)
        print("用户注册成功")

def login_user():
    userdata = read_userdata()
    user, passwd = input("请输入你的用户名："), input("请输入你的密码：")
    r = [x for x in userdata if x["用户名"] == user and x["密码"] == hash_password(passwd)]
    if r and number_check(r[0]["邮箱"]):
        print(f"恭喜，登录成功")
        print(r)
    else:
        print("登录失败")

while True:
    # 执行windows指令，清屏 clear
    os.system("cls")
    print(bar)
    result = input("请输入任务编号：")
    if result == "1":
        login_user()
    elif result == "2":
        reg_user()
    elif result == "3":
        break
    else:
        print("任务不存在")
    input()
print("程序结束")
